/****************************************************************************
 * 2025.10 XLB-20250122JTG
 ****************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
using QFramework;
using QAssetBundle;

namespace ProjectSurvivor
{
	public partial class CoinUpgradePanel : UIElement, IController
	{
		private void Awake()
		{
			CoinUpgradeItemTemplate.Hide();
			
			foreach (CoinUpgradeItem coinUpgradeItem in this.GetSystem<CoinUpgradeSystem>().Items.Where(item => !item.UpgradeFinish))
			{
				var itemCache = coinUpgradeItem;
				
				CoinUpgradeItemTemplate.InstantiateWithParent(CoinUpgradeItemRoot)
					.Self(self =>
					{
						var selfCache = self;
						
						selfCache.GetComponentInChildren<Text>().text = $"{itemCache.Description} 金币 {itemCache.Price}";
						selfCache.onClick.AddListener(() =>
						{
							AudioKit.PlaySound(Sfx.BUTTONCLICK);
							itemCache.Upgrade();
						});
						
						// 判断金币是否足够
						Global.Coin.RegisterWithInitValue(coin =>
						{
							if (coin >= itemCache.Price)
							{
								selfCache.interactable = true;
							}
							else
							{
								selfCache.interactable = false;
							}
						}).UnRegisterWhenGameObjectDestroyed(selfCache);
						
						// 状态改变时，显示与隐藏
						itemCache.OnChanged.Register(() =>
						{
							if (itemCache.ConditionCheck())
							{
								selfCache.Show();
							}
							else
							{
								selfCache.Hide();
							}
						}).UnRegisterWhenGameObjectDestroyed(selfCache);
						
						// 初始状态的显示/隐藏
						if (itemCache.ConditionCheck())
						{
							selfCache.Show();
						}
						else
						{
							selfCache.Hide();
						}
					});
			}
			
			Global.Coin.RegisterWithInitValue(coin =>
			{
				CoinText.text = $"金币：{coin}";
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
			
			BtnClose.onClick.AddListener(() =>
			{
				AudioKit.PlaySound(Sfx.BUTTONCLICK);
				this.Hide();
			});

			this.Hide();
		}

		protected override void OnBeforeDestroy()
		{
		}

		public IArchitecture GetArchitecture()
		{
			return Global.Interface;
		}
	}
}